<?php

/**
 * Uploader_Entry
 *
 * @author vbolshov
 */

namespace km\util;

class Uploader_Entry {
	private $error_code_map = array(
		UPLOAD_ERR_OK => null,
		UPLOAD_ERR_CANT_WRITE => 'Cant write to tmp dir',
		UPLOAD_ERR_EXTENSION => 'File upload stopped by extension',
		UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
		UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
		UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded',
		UPLOAD_ERR_NO_FILE => 'No file was uploaded',
		UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder'
	);
	/**
	 * @var mixed
	 */
	private $key, $index, $name, $type, $tmp_name, $error_str, $error_code, $move_name;
	
	function move($dir)
	{
		if ($this->isError())
		{
			if (UPLOAD_ERR_NO_FILE == $this->error_code) {
				throw new Uploader_NoFileException($this->error_str);
			} else {
				throw new Uploader_UploadFailedException($this->error_str);
			}
		}
		
		if (! is_dir($dir))
		{
			throw new Uploader_UploadFailedException($dir . ': not a directory');
		}
		
		if (! is_writable($dir))
		{
			throw new Uploader_UploadFailedException($dir . ' is not writable');
		}
		
		if (! @copy($this->tmp_name, $dir . '/' . $this->getMoveName()))
		{
			throw new Uploader_UploadFailedException('Unable to copy ' . $this->tmp_name . ' to ' . $dir . '/' . $this->getMoveName());
		}
		
		return $dir . '/' . $this->name;
	}
	
	function setKey($key)
	{
		$this->key = $key;
	}
	
	function getKey()
	{
		return $this->key;
	}
	
	function setIndex($index)
	{
		$this->index = $index;
	}
	
	function getIndex()
	{
		return $this->index;
	}
	
	function setName($name)
	{
		$this->name = $name;
	}
	
	function getName()
	{
		return $this->name;
	}

	function setMoveName($name)
	{
		$this->move_name = $name;
	}

	function getMoveName()
	{
		return $this->move_name ? $this->move_name : $this->name;
	}
	
	function setType($type)
	{
		$this->type = $type;
	}
	
	function getType()
	{
		return $this->type;
	}
	
	function setTmpName($name)
	{
		$this->tmp_name = $name;
	}
	
	function getTmpName()
	{
		return $this->tmp_name;
	}
	
	function setErrorCode($code)
	{
		$this->error_code = $code;
		$this->error_str = $this->error_code_map[$code];
	}
	
	function getErrorCode()
	{
		return $this->error_code;
	}
	
	function setErrorString($str)
	{
		$this->error_str = $str;
	}
	
	function getErrorString()
	{
		return $this->error_str;
	}
	
	function isError()
	{
		return (bool) $this->error_str;
	}
	
	function exists()
	{
		return $this->error_code != UPLOAD_ERR_NO_FILE;
	}
	
}